package com.tek.ding.faceding.widget.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.tek.ding.faceding.R;
import com.tek.ding.faceding.bean.Store;

import org.apache.commons.collections4.CollectionUtils;

import java.util.List;

public class StoreAdapter extends RecyclerView.Adapter implements View.OnClickListener {

    private LayoutInflater layoutInflater;
    private Context context;
    private RecyclerView recyclerView;
    private List<Store> list;

    public StoreAdapter(Context context, RecyclerView recyclerView, List<Store> list) {
        this.layoutInflater = LayoutInflater.from(context);
        this.context = context;
        this.recyclerView = recyclerView;
        this.list = list;
    }

    public void setData(List<Store> list) {
        this.list.clear();
        this.list = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.dialog_list_item, parent, false);
        view.setOnClickListener(this);
        return new StoreViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Store data = list.get(position);
        StoreViewHolder viewHolder = (StoreViewHolder) holder;
        viewHolder.item.setText(data.getStoreName());
        if (position == list.size() - 1) {
            viewHolder.line.setVisibility(View.GONE);
        } else {
            viewHolder.line.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public int getItemCount() {
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        return list.size();
    }

    @Override
    public void onClick(View view) {
        if (onItemClickListener != null) {
            int childAdapterPosition = recyclerView.getChildAdapterPosition(view);
            onItemClickListener.onItemClickListener(list.get(childAdapterPosition));
        }
    }

    class StoreViewHolder extends RecyclerView.ViewHolder {
        TextView item;
        View line;

        public StoreViewHolder(@NonNull View itemView) {
            super(itemView);
            item = itemView.findViewById(R.id.item);
            line = itemView.findViewById(R.id.line);

        }
    }

    public OnItemClickListener onItemClickListener;

    public interface OnItemClickListener {
        void onItemClickListener(Store data);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
}
